package com.example.demo.bean;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.WriteConcern;
import com.mongodb.client.MongoDatabase;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MongoService {

    @Value("${spring.data.mongodb.host}")
    private String mongoDBHost;
    @Value("${spring.data.mongodb.database}")
    private String mongoDatabase;

    @Bean
    public MongoDatabase init(){
//        System.err.println(mongoDBHost);

        MongoClient mongoClient = new MongoClient(mongoDBHost,27017);
        MongoClientOptions.Builder options = new MongoClientOptions.Builder();
//        options.retr
//         options.autoConnectRetry(true);// 自动重连true
//         options.maxAutoConnectRetryTime(10); // the maximum auto connect retry time
        options.connectionsPerHost(300);// 连接池设置为300个连接,默认为100
        options.connectTimeout(15000);// 连接超时，推荐>3000毫秒
        options.maxWaitTime(5000); //
        options.socketTimeout(0);// 套接字超时时间，0无限制
        options.threadsAllowedToBlockForConnectionMultiplier(5000);// 线程队列数，如果连接线程排满了队列就会抛出“Out of semaphores to get db”错误。
        options.writeConcern(WriteConcern.SAFE);//
        options.build();
        MongoDatabase db = mongoClient.getDatabase(mongoDatabase);

        return db;
    }

}
